package com.example.administrator.myapplication;

import android.app.Activity;
import android.app.AlarmManager;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

/**
 * Created by Administrator on 2018/1/3.
 */

public class AddActivity extends Activity {
    //标题内容、时间
    private EditText etName,etMain,etTime;
    //保存 取消按钮
    private Button btnCommit,btnCancel;
    //数据库操作类
    private SQLiteDatabase sdb;
    private ActivityManager am;
    private int year,month,day,hours,mintue,second;

    private Calendar c;
    private PendingIntent pi;
    private AlarmManager alm;

    //编辑模式
    private boolean EDIT = true;
    private String noteID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.add);
        super.onCreate(savedInstanceState);
        am  = ActivityManager.getInstance();
        am.addActivity(this);

        etMain = (EditText) findViewById(R.id.noteMain);
        etName = (EditText) findViewById(R.id.noteName);
        etTime = (EditText) findViewById(R.id.noteTime);

        btnCommit = (Button) findViewById(R.id.btnCommit);
        btnCancel = (Button) findViewById(R.id.btnCancle);

        final Intent intent = getIntent();
        noteID = intent.getStringExtra("noteID");

        if(noteID != null)
            EDIT = true;
        else
            EDIT = false;

        //数据库连接
        sqlListDBConnect sd = new sqlListDBConnect(AddActivity.this);
        sdb = sd.getReadableDatabase();
        if(EDIT) {
            //通过note取得对应的信息
            Cursor c = sdb.query("note", new String[]{"noteID", "noteName", "noteContent", "noteTime"}, "noteID = ?", new String[]{noteID}, null, null, null);
            while (c.moveToNext()) {
                etName.setText(c.getString(c.getColumnIndex("noteName")));
                etMain.setText(c.getString(c.getColumnIndex("noteContent")));
                etTime.setText(c.getString(c.getColumnIndex("noteTime")));
            }
            c.close();
        }

        else{
                etTime.setText(am.returnTime());
            }


       etTime.setOnLongClickListener(new View.OnLongClickListener() {
           @RequiresApi(api = Build.VERSION_CODES.N)
           @Override
           public boolean onLongClick(View v) {
               c= Calendar.getInstance();
               //取得年月日，时分秒
               year = c.get(Calendar.YEAR);
               month = c.get(Calendar.MONTH);
               day = c.get(Calendar.DAY_OF_MONTH);

               hours = c.get(Calendar.HOUR);
               mintue = c.get(Calendar.MINUTE);
               second = c.get(Calendar.SECOND);

               //新建日期选择控件
               DatePickerDialog dpd = new DatePickerDialog(AddActivity.this, new DatePickerDialog.OnDateSetListener() {
                   @Override
                   public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                           String [] time = {"",hours+":"+mintue+":"+second};
                           String [] time2 = etTime.getText().toString().trim().split(" ");
                           if(time2.length == 2){
                               time[1] = time2[1];
                           }
                           String  mo = "",da ="";
                           if(month<9){
                               mo = "0"+(month+1);
                           }
                           else{
                               mo = month+1+"";
                           }
                           if(dayOfMonth<10){
                               da = "0"+dayOfMonth;
                           }else{
                               da =dayOfMonth+"";
                           }
                           etTime.setText(year+"-"+mo+"-"+da+" "+time[1]);
                   }
               },year,month,day);
               dpd.setTitle("设置日期");
               dpd.show();

               return false;
           }
       });
        etTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取得年月日，时分秒
                c= Calendar.getInstance();
                year = c.get(Calendar.YEAR);
                month = c.get(Calendar.MONTH);
                day = c.get(Calendar.DAY_OF_MONTH);

                hours = c.get(Calendar.HOUR_OF_DAY) ;
                mintue = c.get(Calendar.MINUTE);
                second = c.get(Calendar.SECOND);

                TimePickerDialog tpd = new TimePickerDialog(AddActivity.this,new TimePickerDialog.OnTimeSetListener(){
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        String []time  ={year+"-"+month+"-"+day};
                        time = etTime.getText().toString().trim().split(" ");
                        String ho = "",mi ="";
                        if(hourOfDay<10){
                            ho ="0"+hourOfDay;

                        }else{
                            ho= hourOfDay+"";
                        }

                        if(minute<10){
                            mi = "0"+minute;
                        }
                        else{
                            mi = minute + "";
                        }
                        etTime.setText(time[0]+" "+ho+":"+mi);

                    }
                },hours,mintue,true);
                tpd.setTitle("设置时间");
                tpd.show();

            }
        });

        btnCommit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                AlertDialog.Builder adb = new AlertDialog.Builder(AddActivity.this);
                adb.setTitle("保存");
                adb.setMessage("确定要保存吗?");
                adb.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveNote();
                    }
                });
                adb.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(AddActivity.this,"没有保存",Toast.LENGTH_SHORT).show();

                    }

                });
                adb.show();
            }
        });



        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder adb = new AlertDialog.Builder(AddActivity.this);
                adb.setTitle("提示");
                adb.setMessage("确定不保存吗");
                adb.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent1 = new Intent();
                        intent1.setClass(AddActivity.this,MainActivity.class);
                        startActivity(intent1);
                        finish();
                    }
                });
                adb.setNegativeButton("取消",null);
                adb.show();
            }

        });

    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.add(0,1,1,"关于");
        menu.add(0,2,2,"设置闹铃");
        menu.add(0,3,3,"推出");
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId())
        {
            //关于
            case 1:
                AlertDialog.Builder adb = new AlertDialog.Builder(AddActivity.this);
                adb.setTitle("关于");
                adb.setMessage("备忘录 v1.0");
                adb.setPositiveButton("确定",null);
                adb.show();
                break;
                //设置闹铃
            case 2:
                Intent intent = new Intent();
                intent.setClass(AddActivity.this,SetAlarm.class);
                startActivity(intent);
                break;
            case 3:
                AlertDialog.Builder adb1 = new AlertDialog.Builder(AddActivity.this);
                adb1.setTitle("消息");
                adb1.setMessage("确认退出");
                adb1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        am.exitAllProgress();
                    }
                });
                adb1.setNegativeButton("取消",null);
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            AlertDialog.Builder adb = new AlertDialog.Builder(AddActivity.this);
            adb.setTitle("消息");
            adb.setMessage("是否保存");
            adb.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                   saveNote();
                }
            });
            adb.setNegativeButton("不保存",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent();
                    intent.setClass(AddActivity.this,MainActivity.class);
                    startActivity(intent);

                    finish();
                }
            });
            adb.show();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void saveNote(){
        String name = etName.getText().toString().trim();
        String content = etMain.getText().toString().trim();
        String time = etTime.getText().toString().trim();
        //判断是否为空

        if("".equals(name) || "".equals(content)){
            Toast.makeText(this,"名称或者内容不能为空",Toast.LENGTH_SHORT).show();

        }
        else{
            if(EDIT)
            {
                am.saveNote(sdb,name,content,noteID,time);
                Toast.makeText(this,"更新成功",Toast.LENGTH_SHORT).show();

            }
            else{
                am.addNote(sdb,name,content,time);
                Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
            }
            String [] t =etTime.getText().toString().trim().split(" ");
            //分割日期
            String [] t1 = t[0].split("-");
            String [] t2 = t[1].split(":");

            Calendar c2 = Calendar.getInstance();
            //设置日历为闹钟的时间
            c2.set(Integer.parseInt(t1[0]),Integer.parseInt(t1[1])-1,Integer.parseInt(t1[2]),Integer.parseInt(t2[0]),Integer.parseInt(t2[1]));
            c  = Calendar.getInstance();
            if(c.getTimeInMillis()+1000*10<=c2.getTimeInMillis()) {
                String messageContent;
                if (content.length() > 20) {
                    messageContent = content.substring(0, 28) + "...";

                } else {
                    messageContent = content;
                }
                Intent intent = new Intent();
                intent.setClass(this, AlarmNote.class);
                intent.putExtra("messageTitle", name);
                intent.putExtra("messageContent", messageContent);

                pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                alm = (AlarmManager) getSystemService(ALARM_SERVICE);
                //设置一个闹钟
                alm.set(AlarmManager.RTC_WAKEUP,c2.getTimeInMillis(),pi);
            }
            Intent intent2 = new Intent();
            intent2.setClass(this,MainActivity.class);
            startActivity(intent2);
            finish();


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sdb.close();
    }
}
